//
//  ChannelPool.m
//  doubanFun
//
//  Created by bing on 16/3/24.
//  Copyright © 2016年 bing. All rights reserved.
//

#import "DFChannel.h"
#import "ChannelPool.h"
#import "DFChannelDAO.h"

@interface ChannelPool ()
/*!
 *  @brief 频道列表
 */
@property (nonatomic, strong) NSArray *channels;
/*!
 *  @brief 歌曲列表
 */
@property (nonatomic, strong) NSMutableDictionary *channelOfsongData;
@end

@implementation ChannelPool

+ (instancetype)sharedPool {
    static ChannelPool *pool;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        pool = [[self alloc] init];
        pool.channelOfsongData = [NSMutableDictionary dictionary];
    });
    return pool;
}


#pragma mark - channel

- (void)setChannelsArray:(NSArray *)channels {
    if (!channels) {
        return;
    }
    self.channels = channels;
}

- (NSArray *)allChannelsAndSorted {
    /*!
     *  @brief 排序规则,按照 seq_id 排序
     */
    return [self.channels sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        DFChannel *channel1 = (DFChannel *)obj1;
        DFChannel *channel2 = (DFChannel *)obj2;
        if (channel1.seq_id == channel2.seq_id) {
            return [channel1.channel_id integerValue] - [channel2.channel_id integerValue];
        }
        return channel1.seq_id - channel2.seq_id;
    }];
}


#pragma mark - song

- (void)setSongs:(NSArray *)songs channelID:(NSString *)channelID {
    [_channelOfsongData setObject:songs forKey:channelID];
}

- (NSArray *)songListOfChannelID:(NSString *)channelID {
    if (channelID.length < 1) {
        return nil;
    }
    
    return [_channelOfsongData objectForKey:channelID];
}

@synthesize channels = _channels;
- (NSArray *)channels {
    if (!_channels) {
        _channels = [[DFChannelDAO sharedDAO] loadChannelArrayFromDB];
    }
    return _channels;
}

- (void)setChannels:(NSArray *)channels {
    
    // 保存到数据库
    [[DFChannelDAO sharedDAO] saveTODB:channels];
    
    // 本地数据
    _channels = channels;
}

@end
